package com.example.myapplication.module_common_service;

import static com.example.myapplication.module_common_service.FeedBackFragment.OK_ADD_FEED_BACK;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidu.mapapi.http.HttpClient;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.example.myapplication.R;
import com.example.myapplication.data.GlobalData;
import com.example.myapplication.utils.google.zxing.decoding.Intents;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddFeedBackActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_FROM_PHOTO = 1;
    LinearLayout imgArea;
    List<Uri> imgURI = new ArrayList<>();
    BootstrapEditText title ;
    BootstrapEditText content ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_feed_back);
        findViewById(R.id.btn_add_img).setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, REQUEST_CODE_FROM_PHOTO);
        });
        imgArea = findViewById(R.id.img_add_preview);
        findViewById(R.id.cfm_add_fd).setOnClickListener(view -> {
            doAdd();

        });

        title = findViewById(R.id.et_fd_title);
        content = findViewById(R.id.et_fd_content);
    }

    private void doAdd() {
        String title = this.title.getText().toString();
        String content = this.title.getText().toString();
        Random random = new Random();
        OkHttpClient httpClient = new OkHttpClient();
        MultipartBody.Builder   bd = new MultipartBody.Builder();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            this.imgURI.forEach(
                    uri -> {
                        File file = new File(UriToFile(uri));
                        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
                        bd.addFormDataPart("imgs","imgs"+uri,fileBody);
                    }
            );
            MultipartBody multipartBody = bd.setType(MultipartBody.FORM)
                    .addFormDataPart("title", title)
                    .addFormDataPart("content", content)
                    .addFormDataPart("date", LocalDate.now().toString())
                    .addFormDataPart("id", String.valueOf(random.nextInt(20000)))
                    .build();

            String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
            Request getRequest = new Request.Builder()
                    .url("http://120.25.230.35:8080/feedback")
                    .post(multipartBody)
                    .addHeader("jwt",substring)
                    .build();

            Call call = httpClient.newCall(getRequest);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response execute = call.execute();
                        if (execute.isSuccessful()){
                            setResult(OK_ADD_FEED_BACK,null);
                            finish();
                        }else{
                            Toast.makeText(getApplicationContext(),"上传失败！",Toast.LENGTH_LONG).show();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_CODE_FROM_PHOTO:
                if(resultCode == RESULT_OK){
                    try {
                        Uri uri = data.getData();
                        Bitmap imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
                        Uri newUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),imageBitmap,"IMG"+ Calendar.getInstance().getTime(),null));
                        String imgString = UriToFile(newUri);
                        this.imgURI.add(newUri);
                        ImageView imageView = new ImageView(this);
                        imageView.setImageURI(newUri);
                        imgArea.addView(imageView);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
          }
        }

    public String UriToFile(Uri uri) {
        String[] filePc = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, filePc, null, null, null);
        cursor.moveToFirst();
        int col = cursor.getColumnIndex(filePc[0]);
        String pic = cursor.getString(col);
        cursor.close();
        return pic;
    }

}